declare var io;
async function initIO() {

    if (cc.sys.isNative) {

    }
    else {
        // if(window.io == null){
        window.io = await import('./socket-io.js');
        // }
    }
}

initIO();


export class Net {
    static ip = '';
    static sio: io;
    static isPinging = false;
    static fnDisconnect;
    static handlers = {};
    /**游戏延时时间 */
    static delayMS;
    static lastRecieveTime: number;
    static lastSendTime: number;
    static addHandler(event?: cc.game_event_map[keyof cc.game_event_map], fn?) {
        if (this.handlers[event]) {
            console.log('事件：' + event + '已经被注册！');
            return;
        }

        const handler = data => {
            if (event != 'disconnect' && typeof (data) == 'string') {
                data = JSON.parse(data);
            }
            fn(data);
        };

        this.handlers[event] = handler;
        if (this.sio) {
            console.log('注册事件:' + event);
            this.sio.on(event, handler);
        }
    }

    static connect(fnConnect?, fnError?) {
        let opts = {
            'reconnection': false,
            'force new connection': true,
            'transports': ['websocket', 'polling']
        };
        if (CC_JSB) {
            cc.vv.alert.show('111', '222');
            this.sio = io.connect(this.ip, opts);
        }
        else {
            this.sio = window.io.connect(this.ip, opts);
        }
        this.sio.on('reconnect', data => {
            cc.vv.alert.show('重新连接', '');
        });

        this.sio.on('connect', data => {
            cc.vv.alert.show('连接 上了', '');
            this.sio.connected = true;
            fnConnect(data);
        });

        this.sio.on('disconnect', data => {
            console.log('断开连接');
            cc.vv.alert.show('断开连接', '');
            this.sio.connected = false;
            this.close();
        });

        this.sio.on('connect_failed', () => {
            console.log('连接失败');
            cc.vv.alert.show('连接失败', '');
            fnError();
        });

        for (let key in this.handlers) {
            let value = this.handlers[key];
            if (typeof value == 'function') {
                if (key == 'disconnect') {
                    this.fnDisconnect = value;
                }
                else {
                    console.log('注册事件：' + key);
                    this.sio.on(key, value);
                }
            }
        }

        this.startHearbeat();
    }

    /**
     * 更新延迟的显示
     */
    static startHearbeat() {
        this.lastRecieveTime = Date.now();

        if (!this.isPinging) {
            this.isPinging = true;
            cc.game.on(cc.game.EVENT_HIDE, () => {
                this.ping();
            });
            setInterval(() => {
                if (this.sio) {
                    this.ping();
                }
            }, 5000);

            setInterval(() => {
                if (this.sio) {
                    if (Date.now() - this.lastRecieveTime > 1000000000) {
                        this.close();
                    }
                }
            }, 500);
        }

        this.sio.on(cc.vv.game_event_map.GAME_PONG, () => {
            console.log('game_pong');
            this.lastRecieveTime = Date.now();
            this.delayMS = this.lastRecieveTime - this.lastSendTime;
            console.log(this.delayMS);
        });
    }

    static ping() {
        if (this.sio) {
            this.lastSendTime = Date.now();
            this.send(cc.vv.game_event_map.GAME_PING);
        }
    }

    static send(event, data?) {
        if (this.sio.connected) {
            if (data != null && typeof data == 'object') {
                data = JSON.stringify(data);
            }
            this.sio.emit(event, data);
        }
    }

    static close() {
        console.log('关闭连接');
        this.delayMS = null;

        if (this.sio && this.sio.connected) {
            this.sio.connected = false;
            this.sio.disconnect();
        }

        this.sio = null;

        if (this.fnDisconnect) {
            this.fnDisconnect();
            this.fnDisconnect = null;
        }
    }

    /**
     * 检查服务器是否开着呢，1.5秒如果还没返回就当是服务器挂了
     * @param fnResult 
     */
    static test(fnResult) {
        let xhr: XMLHttpRequest = null;
        let fn = (ret) => {
            fnResult(ret.isonline);
            xhr = null;
        };

        let arr = this.ip.split(':');
        let data = {
            account: cc.vv.userMgr.account,
            sign: cc.vv.userMgr.sign,
            ip: arr[0],
            port: arr[1]
        };
        xhr = cc.vv.http.sendRequest('/is_server_online', data, fn);
        setTimeout(() => {
            if (xhr) {
                xhr.abort();
                fnResult(false);
            }
        }, 1500);
    }
}
